<template>
  <div class="category-management">
    <div class="header">
      <a-input-search
          v-model:value="searchText"
          placeholder="请输入分类名称"
          @search="handleSearch"
          class="search-input"
      />
      <a-button type="primary" @click="addCategory" class="add-button">
        新增分类
      </a-button>
    </div>
    <div class="content">
      <a-tree
          :tree-data="displayCategories"
          :field-names="fieldNames"
          :selectable="false"
          default-expand-all
      >
        <template #title="{ name, id }">
          <span class="category-name">{{ name }}</span>
          <span class="actions">
            <a-button type="link" @click="editCategory(id)">编辑</a-button>
            <a-button type="link" @click="deleteCategory(id)">删除</a-button>
          </span>
        </template>
      </a-tree>
    </div>

    <a-modal
        v-model:visible="editModalVisible"
        :title="editModalTitle"
        @ok="handleEditOk"
        :destroy-on-close="true"
    >
      <a-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="名称" name="name">
          <a-input v-model:value="editForm.name" />
        </a-form-item>
        <a-form-item label="父分类" name="parent">
          <a-tree-select
              v-model:value="editForm.parent"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择父分类"
              allow-clear
              tree-default-expand-all
          >
            <a-tree-select-node
                v-for="category in categoryTree"
                :key="category.id"
                :value="category.id"
                :title="category.name"
                :disabled="category.id === editForm.id"
            >
              <a-tree-select-node
                  v-for="child in category.children"
                  :key="child.id"
                  :value="child.id"
                  :title="child.name"
                  :disabled="child.id === editForm.id"
              />
            </a-tree-select-node>
          </a-tree-select>
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="editForm.sort" :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted } from 'vue';
import axios from 'axios';

const url = 'http://127.0.0.1:8888/category/all';

export default defineComponent({
  setup() {
    const categories = ref([]);
    const categoryTree = ref([]);
    const searchText = ref('');
    const editModalVisible = ref(false);
    const editModalTitle = ref('');
    const editForm = ref({});
    const editFormRef = ref(null);

    // 树形控件的字段名称映射
    const fieldNames = {
      children: 'children',
      title: 'name',
      key: 'id',
    };

    // 表单验证规则
    const editFormRules = {
      name: [{ required: true, message: '请输入分类名称' }],
      sort: [{ required: true, message: '请输入排序值' }],
    };

    // 获取分类数据
    const fetchData = async () => {
      try {
        const response = await axios.get(url);
        categories.value = response.data.content;
        categoryTree.value = buildCategoryTree(response.data.content);
      } catch (error) {
        console.error('Failed to fetch data:', error);
        // 给出用户提示
        // message.error('获取分类列表失败,请稍后重试');
      }
    };

    // 构建分类树形结构
    const buildCategoryTree = (categories) => {
      const map = new Map();
      const roots = [];

      // 先将所有分类存入Map,并找出根节点
      categories.forEach((category) => {
        map.set(category.id, {
          ...category,
          children: [],
        });
        if (category.parent === 0) {
          roots.push(category);
        }
      });

      // 再次遍历分类,将子分类放入父分类的children中
      categories.forEach((category) => {
        if (category.parent !== 0) {
          const parentCategory = map.get(category.parent);
          if (parentCategory) {
            parentCategory.children.push(category);
          }
        }
      });

      return roots;
    };

    // 根据搜索条件筛选分类
    const displayCategories = computed(() => {
      const filterCategories = (categories, keyword) => {
        return categories.filter((category) => {
          if (category.name.includes(keyword)) {
            return true;
          }
          if (category.children) {
            category.children = filterCategories(category.children, keyword);
            return category.children.length > 0;
          }
          return false;
        });
      };

      return searchText.value
          ? filterCategories(categoryTree.value, searchText.value)
          : categoryTree.value;
    });

    // 点击搜索按钮时触发
    const handleSearch = () => {
      // 不需要重新获取数据,直接通过computed属性过滤
    };

    // 点击新增分类按钮时触发
    const addCategory = () => {
      editForm.value = {
        sort: 0,
        parent: 0,
      };
      editModalTitle.value = '新增分类';
      editModalVisible.value = true;
    };

    // 点击编辑按钮时触发
    const editCategory = (id) => {
      const category = findCategory(categoryTree.value, id);
      editForm.value = {
        ...category,
      };
      editModalTitle.value = '编辑分类';
      editModalVisible.value = true;
    };

    // 根据id查找分类
    const findCategory = (categories, id) => {
      for (const category of categories) {
        if (category.id === id) {
          return category;
        }
        if (category.children) {
          const foundCategory = findCategory(category.children, id);
          if (foundCategory) {
            return foundCategory;
          }
        }
      }
      return null;
    };

    // 点击删除按钮时触发
    const deleteCategory = async (id) => {
      try {
        await axios.delete(`/category/delete/${id}`);
        fetchData();
      } catch (error) {
        console.error('Delete failed:', error);
        // message.error('删除分类失败,请重试');
      }
    };

    // 点击模态框的确定按钮时触发
    const handleEditOk = () => {
      editFormRef.value
          .validate()
          .then(async () => {
            try {
              await axios.post('/category/save', editForm.value);
              editModalVisible.value = false;
              fetchData();
            } catch (error) {
              console.error('Save failed:', error);
              // message.error('保存分类失败,请重试');
            }
          })
          .catch((error) => {
            console.error('Validate failed:', error);
          });
    };

    onMounted(() => {
      fetchData();
    });

    return {
      displayCategories,
      categoryTree,
      searchText,
      editModalVisible,
      editModalTitle,
      editForm,
      editFormRef,
      editFormRules,
      fieldNames,
      handleSearch,
      addCategory,
      editCategory,
      deleteCategory,
      handleEditOk,
    };
  },
});
</script>

<style scoped>
.category-management {
  max-width: 800px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  max-width: 300px;
}

.add-button {
  margin-left: 10px;
}

.content {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 20px;
}

.category-name {
  margin-right: 10px;
}

.actions {
  display: inline-block;
}
</style>